package com.jay.lang.instrument.preagent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class SimpleTransformer implements ClassFileTransformer {
	public SimpleTransformer() {
		super();
	}

	@Override
	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		System.out.println("Transformer to Transform Class: " + className);
		if (!className.endsWith("MyMain")) {
			return null;
		}
		String line = "";
		//for-each不用于改变值,b为临时变量，复制的是值
		// for (Byte b : classfileBuffer) {
		// line += Byte.toString(b) + " ";
		// if (line.length() >= 60) {
		// System.out.println(line);
		// line = "";
		// }
		// if (b == (byte)6) {
		// b = (byte)7;
		// }
		// }
		for (int i = 0; i < classfileBuffer.length; i++) {
			line += Byte.toString(classfileBuffer[i]) + " ";
			if (line.length() >= 60) {
				System.out.println(line);
				line = "";
			}
			//网上的例子，乱改字节码怎么可以
			if (classfileBuffer[i] == (byte) 6) {
				classfileBuffer[i] = (byte) 7;
			}
		}
		System.out.println(line);
		System.out.println("The number of bytes in class MyMain is "
				+ classfileBuffer.length);

		return classfileBuffer;
	}

}
